<template>
	<view class="content">
		
		<NavBar :title="title" :autoBack="false" id="nav">
			<template #left>
				<view class="navbar-left center" @click="goBack">
					<u-icon name="arrow-left" color="#007aff" size="34"></u-icon>
					<text class="c007aff">{{lefttitle}}</text>
				</view>
			</template>
			<template #right>
				<view v-if="info.ident!=3" class="navbar-right c007aff center" @click="subInfo">
					save
				</view>
			</template>
			
		</NavBar>
		<view class="widths main">
			<view class="list">
				<view class="flex item">
					<view class="label">進度分數</view>
					<view class="center val">
						<u-input class="input" input-align="right"  :disabled="info.disabled" :show-confirmbar="false" v-model="info.cost" maxlength=4 type="text" placeholder="進度分數" placeholder-style="color:#e0e0e0;" />
					</view>
				</view>
				<view class="flex item">
					<view class="label">延遲狀態
						<!-- <text v-if="info.delay>0" class="ml-10 f24 c007aff">延遲{{info.delay}}天</text> -->
						<!-- <text v-if="info.delay<0" class="ml-10 f24 c007aff">提前{{Math.abs(info.delay)}}天</text> -->
					</view>
					<view class="center val">
						<u-switch :disabled="info.disabled" v-model="info.isdelay" @change="selectIsdelay" active-color="#007aff" ></u-switch>
					</view>
				</view>
				<view class="flex item">
					<view class="label">記錄日期</view>
					<view class="center val" @click="showTime">
						{{info.time}}
					</view>
				</view>
				<view class="flex item notebox">
					<view class="label">Note</view>
					<view class="val">
						<view class="txtbox">
							<u-input class="input"  :disabled="info.disabled" v-model="info.detail" type="textarea" input-align="left" :show-confirmbar="false"  maxlength=1000  placeholder="請輸入內容" placeholder-style="color:#e0e0e0;" 
								height="360"
							/>
						</view>
					</view>
				</view>
				<!-- <view class="flex item upbox">
					<view class="start picbox">
						<view class="pic" v-for="(v,k) in info.thumb" :key="k">
							<image :src="v" width="200rpx" height="160rpx" mode="aspectFit" border-radius="16rpx"></image>
						</view>
						
					</view>
				</view> -->
				<view class="flex item upbox">
					<view class="picbox">
						<view class="pic" v-for="(v,k) in info.thumb" :key="k">
							<u-icon class="delpic" v-if="info.ident != 3" name="minus-circle-fill" color="#f00" size="36" @click="delpic(k)"></u-icon>
							<!-- <u-image :src="v" width="200rpx" height="180rpx" mode="aspectFill" border-radius="16rpx"></u-image> -->
							<image  :src="v.pic" width="200rpx" height="160rpx" mode="aspectFit" border-radius="16rpx" @click="viewImg(info.thumb,k)"></image>
							<view class="pic-remark">
								<uni-easyinput type="textarea" v-model="v.memo" placeholder="請輸入備註" />
							</view>
						</view>
						<view class="center uppic" v-if="info.ident!=3 && info.thumb && info.thumb.length<9" @click="uppic">
							<view class="center uppicborder">
								<u-icon name="plus" color="#007aff" size="60"></u-icon>
							</view>
							
						</view>
					</view>
					
				</view>
				
				<view class="mt-20 center btnbox">
					<!-- <a class="btn" v-if="isPc" :href="info.pdf">查看PDF</a> -->
					<view  v-if="info.pdf" class="btn" @click="copyPdf(info.pdf)" >查看PDF</view>
					<view  v-if="info.word" class="btn" @click="downLoadWord(info.word)" >下載word</view>
				</view>
			</view>
			
			
		</view>
		<u-picker mode="time" start-year="2020"  v-model="timeShow"
			@confirm="selectTime"
			confirm-text="確認"
			:default-time="date.defaultTime"
		></u-picker>
		<Tabar></Tabar>
	</view>
</template>

<script>
	import { getLogDetail,updateTasksLog,generateTaskLogPdfFiile } from "@/api/apis.js"
	import NavBar from "@/component/NavBar"
	import Tabar from "@/component/HomeTab"
	import {
		baseUrl
	} from "@/api/url.js"
	export default {
		components:{
			NavBar,
			Tabar
		},
		data() {
			return {
				isPc:false,
				action: baseUrl + '/api/apict/uploadfile',
				curId:0,
				title:"",
				lefttitle:"",
				info:{
					delay:0,
					isdelay:false,
				},
				taskInfo:{},
				date:{
					year:0,
					month:0,
					day:0,
					timestamp:'',
					defaultTime:'',
				},
				timeShow:false,
			}
		},
		onShow(){
			
			const app = getApp();
			this.isPc=app.globalData.isPc
			this.$nextTick(()=>{
				if(!uni.getStorageSync("islogin")){
					setTimeout(()=>{
						this.toPage("Home")
					},1200)
				}
			})
		},
		
		onLoad() {
			if(uni.getStorageSync("islogin")){
				const { id } = this.$Route.query
				if(!id){
					this.$Errback("數據錯誤")
				}else{
					this.curId=id;
					this.init()
				}
			}else{
				this.$Toast("請先登錄")
				setTimeout(()=>{
					this.toPage("Home")
				},1200)
			}
			
		
		},
		methods: {
			showTime(){
				if(this.info.ident == 3) return;
				this.timeShow=true
			},
			selectIsdelay(e){
				this.info.isdelay=e?1:0;
			},
			copyPdf(path){
				// console.log(path)
				let _this=this
				uni.setClipboardData({
					data: path,
					success: function () {
						_this.$Toast("复制成功")
					},
					fail: function (err) {
						_this.$Toast("复制失败")
					}
				});
				this.toPage("Pdf",{path})
			},
			downLoadWord(filePath){
				// uni.downloadFile({
				// 	url: path,
				// 	success: function (res) {
				// 		if (res.statusCode === 200) {
				// 			this.$Toast("下载成功")
				// 			// uni.saveFile({
				// 			// 	tempFilePath: res.tempFilePath,
				// 			// 	success: function (res) {
				// 			// 		uni.openDocument({
				// 			// 			filePath: res.savedFilePath,
				// 			// 			fileType:'docx',
				// 			// 			success: function (res) {
				// 			// 				console.log('打开文档成功')
				// 			// 			},
				// 			// 			fail:function(err){
				// 			// 				console.log(err)
				// 			// 			}
				// 			// 		})
				// 			// 	}
				// 			// })
				// 		}
				// 	}
				// });
				// const filePath = `/api/file/downloadByType/${res.fileId}`;
				let nameArr = filePath.split("/")
				let fileName = nameArr[nameArr.length-1]

				const tempLink = document.createElement("a");
				tempLink.style.display = "none";
				tempLink.href = filePath;
				tempLink.setAttribute("download", fileName);
				tempLink.setAttribute("target", "_blank");
				document.body.appendChild(tempLink);
				tempLink.click();
				document.body.removeChild(tempLink);
			},
			viewImg(images,i){
				console.log(images,i)
				let imgUrlArr = []
				images.forEach(item=>{
					imgUrlArr.push(item.pic)
				})
				uni.previewImage({
					current:i,
					urls: imgUrlArr,
					indicator:'number',
					longPressActions: {
						// itemList: ['发送给朋友', '保存图片', '收藏'],
						// success: function(data) {
						// 	console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						// },
						// fail: function(err) {
						// 	console.log(err.errMsg);
						// }
					}
				});
			},
			getCurDate(){
				var date = new Date(),
					year = date.getFullYear(), //年
					month = date.getMonth() + 1, //月
					day = date.getDate(), //日
					days = date.getDay();
				this.date.defaultTime=	year+"/"+month+"/"+day
				this.date.timestamp=Math.floor(Date.parse(year+"/"+month+"/"+day)/1000);
				this.info.timestamp=Math.floor(Date.parse(year+"/"+month+"/"+day)/1000);
				this.date.year=year;
				this.date.month=month;
				this.date.day=day;
				this.info.time = year+'年'+month+'月'+day+'日'
			},
			selectTime(e){
				this.info.time=e.year+"年"+parseInt(e.month)+"月"+parseInt(e.day)+'日';
				this.info.timestamp=this.timeTotimestamp(e.year+"/"+parseInt(e.month)+"/"+parseInt(e.day))
				this.date.defaultTime=e.year+"/"+e.month+"/"+e.day
				// if(this.info.timestamp > this.info.endtime){
				// 	this.info.isdelay=true
				// 	this.info.delay=Math.ceil((this.info.timestamp - this.info.endtime)/86400)
				// }else{
				// 	this.info.isdelay=false
				// }
			},
			timeTotimestamp(str){
				return Math.floor(Date.parse(str)/1000);
			},
			timeTostr(str){
				let arr = str.split("/");
				let month = parseInt(arr[0]);
				let day = parseInt(arr[1]);
				let year = parseInt(arr[2]);
				month = month>9?month:'0'+month
				day = day>9?day:'0'+day
				return year+"/"+month+"/"+day
			},
			init(){
				let uid = uni.getStorageSync("uid")
				getLogDetail({id:this.curId,uid}).then((res)=>{
					this.lefttitle=res.time
					if(!res.thumb){
						res.thumb=[]
					}
					this.info=res
					this.date.defaultTime=res.defaultTime
					this.info.timestamp=res.logtime
				}).catch((err)=>{
					if(err.code === 102){
						this.$ClearLogin(err.msg)
					}else{
						this.$Toast(err.msg)
					}
				})
			},
			uppic(){
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						this.$Loading("上传中")
						let uploadedCount = 0;
						tempFilePaths.forEach((item)=>{
							uni.uploadFile({
								header:{
									'token':uni.getStorageSync('userToken')
								},
								url: this.action, //仅为示例，非真实的接口地址
								filePath: item,
								formData: {
									uid: uni.getStorageSync("uid")
								},
								name: 'file',
								success: (uploadFileRes) => {
									let data = JSON.parse(uploadFileRes.data);
									if(data.data.code===1){
										// this.info.pic = data.data.url
										this.info.thumb.push({
											pic:baseUrl+data.data.url,
											memo:""
										})
									}else{
										this.$Toast(data.msg)
									}
								},
								fail:(err)=>{
									this.$Toast(err.msg)
								},
								complete: () => {
								  uploadedCount++; 
								  if (uploadedCount === tempFilePaths.length) { 
									this.$Toast("上传成功")
								  }else{
									uni.hideLoading()
								  }
								}
							});
						})
						
					}
				});
			},
			subInfo(){
				if(this.info.cost<0){
					this.$Toast("進度分數不能小于0")
					return 
				}
				if(!/^\d*$/.test(this.info.cost)){
					this.$Toast("请输入正确的分數")
					return 
				}
				if(this.info.cost > this.info.max){
					this.$Toast("進度分數最大为"+this.info.max)
					return 
				}
				if(this.info.days > this.taskInfo.progress_plan){
					this.$Toast("該任務最大進度分數為"+this.taskInfo.progress_plan+"分")
					return 
				}
				// if(!this.info.detail){
				// 	this.$Toast("Note不能為空")
				// 	return 
				// }
				
				let data = {
					id:this.curId,
					tid:this.info.tid,
					uid:uni.getStorageSync("uid"),
					cost:this.info.cost,
					time:this.info.timestamp,
					detail:this.info.detail,
					delay:this.info.isdelay?1:0,
				}
				if(this.info.thumb.length>0) {
					data.thumb= JSON.stringify(this.info.thumb)
				}else{
					data.thumb="[]"
				}
				// console.log("info",this.info)
				// console.log("data",data)
				this.$Loading()
				updateTasksLog(data).then((res)=>{
					uni.hideLoading()
					this.generatePdf()
					this.$Errback(res.msg);
				}).catch((err)=>{
					uni.hideLoading()
					if(err.code === 102){
						this.$ClearLogin(err.msg)
					}else{
						this.$Toast(err.msg)
					}
				})
				
			},
			//生成pdf
			generatePdf(){
				let data = {
					taskLogId:this.curId,
					uid:uni.getStorageSync("uid"),
				}
				generateTaskLogPdfFiile(data).then((res)=>{
					console.log(res)
				}).catch((err)=>{
					console.log(err)
				})
			},
			delpic(i){
				this.info.thumb.splice(i, 1);
			},
			goBack(){
				uni.navigateBack(-1)
			},
			toPage(name,params={}){
				this.$navi({
				    route:{
				        name,
						params
				    },
				})
			}
		}
	}
</script>

<style lang="scss">
	.content{
		min-height: 100vh;
	}
	.main{
		padding-top: 128rpx;
		.list{
			.item{
				padding: 8rpx 0;
				align-items: center;
				/deep/ .u-switch--disabled{
					opacity: 1 !important;
				}
				.val{
					height: 60rpx;
				}
				&.notebox{
					flex-wrap: wrap;
					margin-top: 20rpx;
					.label{
						flex-basis: 100%;
						margin-bottom: 10rpx;
					}
					.val{
						width: 100%;
						height: 400rpx;
						background-color: #f1f1f1;
						border-radius: 10rpx;
						padding: 20rpx;
						
						.txtbox{
							width: 100%;
							height: 360rpx;
							overflow: scroll;
						}
					}
				}
				&.upbox{
					margin-top: 30rpx;
					justify-content: start;
					.uppic{
						flex-shrink: 0;
						width: 200rpx;
						height: 160rpx;
						.uppicborder{
							width: 120rpx;
							height: 120rpx;
							border: 6rpx solid #007aff;
							border-radius: 50%;
						}
					}
					.picbox{
						width: 100%;
						position: relative;
						display: flex;
						flex-wrap: wrap;
						gap: 20rpx;
						.pic{
							// margin-right: 30rpx;
							position: relative;
							width: 100%;
							box-sizing: border-box;
							display: flex;
							align-items: center;
							// height: 160rpx;
							margin-bottom: 30rpx;
							padding: 20rpx;
							border-radius: 8rpx;
							border: #f5f5f5 2rpx solid;
							/deep/ uni-image{
								width: 180rpx !important;
								height: 180rpx !important;
								margin-right: 20rpx;
							}
							.delpic{
								position: absolute;
								top:-18rpx;
								right: -18rpx;
								z-index: 3;
							}
							.pic-remark{
								flex: 1;
							}
						}
						
					}
				}
			}
			.btnbox{
				margin-top: 50rpx;
				padding-bottom: 40rpx;
				.btn{
					text-decoration: none;
					font-size: 26rpx;
					padding: 16rpx 30rpx;
					background-color: #007aff;
					color: #fff;
					border-radius: 8rpx;
					box-shadow: 2rpx 2rpx 6rpx rgba(9,100,199,1);
					&:first-child{
						margin-right: 20rpx;
					}
				}
			}
		}
	}
</style>
